package com.tim.android.widget.cardview;

import static android.graphics.Paint.ANTI_ALIAS_FLAG;

import com.tim.android.widget.cardview.CardViewContainer.OnSwitchCardListener;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

public class CardViewIndicator extends View implements OnSwitchCardListener {
	
	private final String TAG = "CardViewIndicator";
	
	private float mRadius;
    private final Paint mPaintStroke = new Paint(ANTI_ALIAS_FLAG);
    private final Paint mPaintFill = new Paint(ANTI_ALIAS_FLAG);
    
    private final int mFillColor = 0xFFFFFFFF;
    private final int mStrokeColor = 0xFF777777;
    
    private CardViewContainer mCardViewContainer;

	public CardViewIndicator(Context context) {
		this(context, null);
	}

	public CardViewIndicator(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}
	
	public CardViewIndicator(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mPaintFill.setStyle(Style.FILL);
		mPaintFill.setColor(mFillColor);
		mPaintStroke.setStyle(Style.FILL);
		mPaintStroke.setColor(mStrokeColor);
		mRadius = 3 * context.getResources().getDisplayMetrics().density + 0.5f;	//3dp
	}

	@Override
	protected void onDraw(Canvas canvas) {
		Log.d(TAG, "<!-- onDraw -->");
		super.onDraw(canvas);
		if(mCardViewContainer != null) {
			int cardSize = mCardViewContainer.getCardViewSize();
			int width = getWidth();
			int paddingLeft = getPaddingLeft();
			int paddingRight = getPaddingRight();
			int paddingTop = getPaddingTop();
			float threeRadius = 3 * mRadius;
			float center = ((width - paddingLeft - paddingRight) / 2.0f) - ((cardSize * threeRadius) / 2.0f);
			
			//--Draw stroke
			for(int i = 0; i < cardSize; i++) {
				float cx = center + (i * threeRadius);
				float cy = paddingTop + mRadius;
				canvas.drawCircle(cx, cy, mRadius, mPaintStroke);
			}
			
			//--Draw fill
			float cx = center + mCardViewContainer.getIndex() * threeRadius;
			float cy = paddingTop + mRadius;
			canvas.drawCircle(cx, cy, mRadius, mPaintFill);
		}
	}
	
	public void setCardViewContainer(CardViewContainer cardViewContainer) {
		mCardViewContainer = cardViewContainer;
		if(mCardViewContainer != null) {
			mCardViewContainer.setOnSwitchCardListener(this);
		}
	}

	@Override
	public void onSwitchCard() {
		invalidate();
	}
}
